package com.alt.ui;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.alt.R;
import com.alt.base.ALTTabActivity;
import com.alt.handler.CMCmdHandler;
import com.alt.manager.ALTAppMgr;
import com.alt.manager.ALTPTCMgr;
import com.alt.manager.ALTPTCMgr.SCREEN_UI;
import com.alt.models.TransactionData;
import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.FacebookRequestError;
import com.facebook.HttpMethod;
import com.facebook.LoggingBehavior;
import com.facebook.Request;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.OpenRequest;
import com.facebook.SessionState;
import com.facebook.Settings;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.internal.Utility;
import com.facebook.widget.WebDialog;
import com.facebook.widget.WebDialog.OnCompleteListener;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ALTShareFriend extends ALTTabActivity implements OnClickListener {

	private TextView tvNameUser;
	private ImageView imgFace;
	private ImageView imgMassage;
	String message;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.share_friend_layout);
		onSetScreenMode(SCREEN_UI.SHAREFRIEND);
		tvNameUser = (TextView) findViewById(R.id.tvNameUser);
		imgFace = (ImageView) findViewById(R.id.imgFace);
		imgMassage = (ImageView) findViewById(R.id.imgMassage);
		initData();

	}

	private void initData() {
		tvNameUser.setText(ALTAppMgr.getInstance().getUserLogInfo().Username);
		imgFace.setOnClickListener(this);
		imgMassage.setOnClickListener(this);

	}

	@Override
	public void onClick(View arg0) {
		if (arg0 == imgFace) {
			// Intent i = new Intent(this,com.facebook.LoginActivity.class);
			// startActivity(i);
			// createFacebookConnection();

			if (ALTAppMgr.isStillLogin || ALTAppMgr.isLoginFace) {
				showDialogConfirm(this.getParent(), "Share on Facebook?");

			} else {
				Toast.makeText(ALTShareFriend.this, "You must login Facebook!", Toast.LENGTH_SHORT).show();
			}
		}
		if (arg0 == imgMassage) {
			// onEventReceiver(SCREEN_UI.LOGIN);
			// createFacebookConnection();
		}

	}

	public void showDialogConfirm(final Context context, final String message) {
		AlertDialog.Builder builder = new Builder(context);
		builder.setTitle(getString(R.string.title_activity_main));
		builder.setMessage(message).setNeutralButton(getString(R.string.txt_btn_ok), new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				createFacebookConnection();
				dialog.dismiss();
			}
		});
		builder.setPositiveButton(getString(R.string.txt_btn_cancel), new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface arg0, int arg1) {
				arg0.dismiss();
			}
		});
		AlertDialog alert = builder.create();
		alert.setCancelable(false);
		alert.setCanceledOnTouchOutside(false);
		alert.show();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
		Log.v("HAI", "eeeeeee");
	}

	public void createFacebookConnection() {
		Session session = new Session(ALTShareFriend.this);
		Session.setActiveSession(session);

		Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

		Session.StatusCallback statusCallback = new Session.StatusCallback() {
			@Override
			public void call(Session session, SessionState state, Exception exception) {
				String message = "Facebook session status changed - " + session.getState() + " - Exception: " + exception;
				Log.w("Facebook test", message);

				if (session.isOpened() || session.getPermissions().contains("publish_actions")) {
					publishToWall();
				} else if (session.isOpened()) {
					OpenRequest open = new OpenRequest(ALTShareFriend.this).setCallback(this);
					List<String> permission = new ArrayList<String>();
					permission.add("publish_actions");
					permission.add("publish_stream");
					permission.add("status_update");
					open.setPermissions(permission);
					Log.v("HAI", "Open for publish");
					session.openForPublish(open);
				}
			}
		};

		if (!session.isOpened() && !session.isClosed() && session.getState() != SessionState.OPENING) {
			session.openForRead(new Session.OpenRequest(ALTShareFriend.this).setCallback(statusCallback));
		} else {
			Log.v("HAI", "Open active session");
			Session.openActiveSession(ALTShareFriend.this, true, statusCallback);
		}
	}

	void publishToWall() {
		Session session = Session.getActiveSession();

		Bundle postParams = new Bundle();
		postParams.putString("name", "NhapNhap");
		postParams.putString("caption", "Digipay");
		postParams.putString("description", "Nhap Nhap application.");
		postParams.putString("link", "http://www.digipay.vn");
		postParams.putString("picture", "http://www.saigonland24h.com/ic_launcher.png");
		Log.i("DIALOG", "feed set");

		Request.Callback callback = new Request.Callback() {
			public void onCompleted(Response response) {
				FacebookRequestError error = response.getError();
				if (error != null) {
					Toast.makeText(ALTShareFriend.this, error.getErrorMessage(), Toast.LENGTH_SHORT).show();
				} else {
					JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
					String postId = null;
					try {
						postId = graphResponse.getString("id");
					} catch (JSONException e) {
						Log.i("Facebook error", "JSON error " + e.getMessage());
					}
					Toast.makeText(ALTShareFriend.this, "Posted on wall success!", Toast.LENGTH_SHORT).show();
					// showdialog();
				}
			}
		};

		Request request = new Request(Session.getActiveSession(), "me/feed", postParams, HttpMethod.POST, callback);

		RequestAsyncTask task = new RequestAsyncTask(request);
		task.execute();
	}

	private void showdialog() {
		AlertDialog.Builder builder;
		builder = new AlertDialog.Builder(this);
		builder.setMessage("Posted on wall success!").setNeutralButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(final DialogInterface dialog, final int id) {
				// Do nothing.\

			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

}
